﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StringExtensions.cs" company="Data Ductus Malmö">
//   (c) 2010 - 2012 Data Ductus Malmö AB
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace DataDuctus.Snmp.Persistor.Core.Extensions
{
  using System;
  using System.Net;
  using System.Net.Sockets;

  /// <summary>
  /// The string extensions.
  /// </summary>
  public static class StringExtensions
  {
    #region Public Methods and Operators

    /// <summary>
    /// The to ip address.
    /// </summary>
    /// <param name="ipAddress">
    /// The ip address.
    /// </param>
    /// <returns>
    /// The System.Net.IPAddress.
    /// </returns>
    /// <exception cref="ArgumentException">If apaddress is not valid.</exception>
    public static IPAddress ToIpAddress(this string ipAddress)
    {
      IPAddress ip;
      bool parsed = IPAddress.TryParse(ipAddress, out ip);
      if (!parsed)
      {
        foreach (IPAddress address in Dns.GetHostAddresses(ipAddress))
        {
          if (address.AddressFamily != AddressFamily.InterNetwork)
          {
            continue;
          }

          ip = address;
          break;
        }

        if (ip == null)
        {
          throw new ArgumentException(
            string.Format("invalid host or wrong IP address found = {0}", ipAddress), "ipAddress");
        }
      }

      return ip;
    }

    #endregion
  }
}